package starsauth.com.kc.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import common.common.Util.JWTutil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

public class TokenFilter implements GlobalFilter, Ordered {

    /**
     * 网关拦截如果没有token设置状态码为401，返没有权限信息。
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        String token = exchange.getRequest().getHeaders().getFirst("AccessToken");

        if (token==null||token.isEmpty()){
            //设置状态码以及权限没有信息。
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            ServerHttpResponse response = exchange.getResponse();
            ObjectMapper mapper = new ObjectMapper();
            String msg = "没有登录无法访问。";
            byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bytes);
            response.getHeaders().add("Content-Type", "text/json;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }else{
            //判断是否是有效token
            boolean falg = JWTutil.Analysis(token);
            if (falg){
                exchange.getResponse().setStatusCode(HttpStatus.OK);
                ServerHttpRequest request = exchange.getRequest().mutate().headers(HttpHeaders->{
                    HttpHeaders.add("tokenYes","OK");
                    HttpHeaders.add("AccessToken",token);
                }).build();
                ServerWebExchange build = exchange.mutate().request(request).build();
                return chain.filter(build);
            }
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -200;
    }
}
